//
//  InputPhoneCode.swift
//  Auto114
//
//  Created by yb on 2020/9/1.
//  Copyright © 2020 RMCtl. All rights reserved.
//

import UIKit


class InputPhoneCode: NSObject, UITextFieldDelegate {
    static let shared = InputPhoneCode()
    var input: UITextField? {
        didSet {
            input?.delegate = self
        }
    }
    var currentCompleteHandler: ((String) -> Void)?
    func getUserInput(complete: @escaping (String) -> Void) {
        guard let inputField = input else {
            return
        }
        inputField.becomeFirstResponder()
        currentCompleteHandler = complete
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string.count == 6, Int(string) != nil {
            currentCompleteHandler?(string)
            currentCompleteHandler = nil
            textField.resignFirstResponder()
        } else {
            DispatchQueue.main.async {
                guard let text = textField.text, text.count == 6, Int(text) != nil else {
                    return
                }
                self.currentCompleteHandler?(text)
                self.currentCompleteHandler = nil
                textField.resignFirstResponder()
            }
        }
        return true
    }
}
